<template>
  <div class="app-container">
    <!-- {{rowData}} -->
    <el-row class="lookUp">
      <el-col :span ="24" >订单号：{{rowData.orderNo}}</el-col>
      <el-col :span ="24" class="marginTop20">
        <Progress :userRole="'boxHuiDiao_agent'" :orderStatus="rowData.status" :payStatus="5" :returnedPay="rowData.returnedPay" :progressConfig="progressConfig"></Progress>
      </el-col>
   </el-row>

    <el-row style="margin: 10px">
      <el-button-group v-if="param.newStep >= 10">
        <el-button icon="edit" @click="showPacking">查看提箱单</el-button>
        <!-- <el-button icon="edit" @click="downloadFile">下载提箱单</el-button> -->
      </el-button-group>
      <el-button-group v-if="isAgent && param.newStep >= 20 && param.newStep <= 25" style="margin-left:20px; ">
        <el-button icon="edit" @click="showReturnInfo">查看还箱单</el-button>
        <!-- <el-button icon="edit" @click="param.drawer2 = true">下载还箱单</el-button> -->
      </el-button-group>
    </el-row>

    <el-card> <!--回调信息-->
      <el-row style="font-weight: 700;font-size: 15px;">
        <el-col :span="12">回调信息</el-col>
      </el-row>
      <stamp v-if="![20, 25, 30, 35, 40, 45].includes(rowData.processBusinessType)" :rowData="rowData" :rentSource="5"
        :pageType="'callBackBox'" style="margin:10px 50px;" />
      <stampCancel v-else :rowData="rowData" :pageType="'callBackBox'" :canceledType="rowData.canceledType"
        :roleType="isAgent ? 'agent' : 'boxEast'" style="margin:10px 50px;" />
      <el-row style="margin: 20px 0;">
        <el-col :span="5" class="text-center">
          <span>出发城市</span>
          <span style="margin-left: 20px;font-weight: 600;">{{rowData.carryCityName}}</span>
        </el-col>
        <el-col :span="12" class="alignCenter"><el-icon><Right /></el-icon></el-col>
        <el-col :span="5" class="alignCenter">到达城市</el-col>
        <!-- <el-col :span="2" class="alignCenter"></el-col> -->
      </el-row>
      <el-row>
        <el-col :span="24">
            <huiDiaoPriceList :priceList="param.priceList" :returnCityList="param.returnCityList" :rowData="rowData"
              :isDisabled="isDisabled" :isAgent="isAgent" :pageState="pageState" @priceListChange="priceListChange">
            </huiDiaoPriceList>
        </el-col>
        <el-col :offset="19" :span="3" class="marginTop20"> 
          <el-button v-if="isShowCheck2" @click="handleShowCheck2" type="primary">确认</el-button>
        </el-col>
      </el-row>

      <el-row style="margin: 30px 0;border-top: 1px solid #ccc;padding-top: 20px;">
        <template v-if="rowData.status == 20">
          <el-col :offset="14" :span="4">待还回调箱量：
            {{rowData.boxQuantity - needsReturnQuantity}} 个
          </el-col>
        </template>
        <template v-if="rowData.status != 20">
          <el-col :span="18"></el-col>
        </template>
        <el-col :span="6">总回调箱量：
          {{ rowData.boxQuantity }} 个
        </el-col>
      </el-row>
    </el-card>

    <el-card class="marginTop20"> <!--回调箱信息-->
      <el-row style="font-weight: 700;font-size: 15px;">
        <el-col :span="12">回调箱信息</el-col>
      </el-row>
      <!-- {{param.priceList}} -->
      <el-row v-if="rowData.status == 20">
        <el-col :span="24">
          <el-row class="marginTop20">
            <el-col :span="4" class="text-right">箱使期：</el-col>
            <el-col :span="4" class="">
              {{ param.priceList[0]?.boxUsagePeriod }} 天
            </el-col>
            <el-col :span="4"  class="text-right">箱型：</el-col>
            <el-col :span="4">{{ { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }[param.priceList[0]?.boxType] }}</el-col>
            <el-col :span="4"  class="text-right">箱况：</el-col>
            <el-col :span="4">{{ { 5: '全新', 10: '次新', 15: '适货', 20: '混提' }[param.priceList[0]?.boxCondition] }}</el-col>
          </el-row>
          <el-row class="marginTop10">
            <el-col :span="4"  class="text-right">预计回调日期：</el-col>
            <el-col :span="4">{{ param.planPickupDate }}</el-col>
            <el-col :span="4"  class="text-right">下单日期：</el-col>
            <el-col :span="4">{{ param.createTime }}</el-col>
            <el-col :span="4"  class="text-right">支付方式：</el-col>
            <el-col :span="4">{{ { 5: '对公转账', 10: '在线支付' }[param.paymentMethod] }}</el-col>
          </el-row>
          <el-row class="marginTop10">
            <el-col :span="4"  class="text-right">结算账期：</el-col>
            <el-col :span="4">{{param.period}} 天</el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row v-else  style="margin-top: 10px;">
        <el-col :span="4" align="middle">
          <img :src="mainFileList[0].url" v-if="mainFileList.length > 0 && mainFileList[0].url"
            style="height: 100px;width: 150px;" />
        </el-col>
        <el-col :span="20" v-if="param.priceList">
            <el-row class="marginTop">
              <el-col :span="2" class="alignRight">箱使期：</el-col>
              <el-col :span="4" class="alignLeft">
                <input class="text-center numberlColor" v-model="param.boxUsagePeriod" @input="cheangeBoxUsagePeriod" v-if="!isDisabled"
                  style="max-width:50px; border: none; outline: none;border-bottom:1px solid black;" />

                <span v-else>{{ param.priceList[0]?.boxUsagePeriod }}</span>天 
              </el-col>
              <el-col :span="2" class="alignRight">预计提箱日期：</el-col>
              <el-col :span="4" class="alignLeft">{{ param.planPickupDate }}</el-col>
              <el-col :span="2" class="alignRight">结算账期：</el-col>
              <el-col :span="4" class="alignLeft">
                <template v-if="rowData.status > 2">
                  <span>{{param.period}}天</span>
                </template>
                <template v-else>
                  <template v-if="isAgent">
                    <span>{{param.period}}天</span>
                  </template>
                  <template v-else>
                    <input class="text-center numberlColor" v-model="param.period" style="max-width:50px; border: none; outline: none;border-bottom:1px solid black;">天
                  </template>
                </template>

              </el-col>
            </el-row>
            <el-row class="marginTop">
              <el-col :span="2" class="alignRight">箱况：</el-col>
              <el-col :span="4" class="alignLeft">{{ { 5: '全新', 10: '次新', 15: '适货', 20: '混提' }[param.priceList[0]?.boxCondition] }}</el-col>
              <el-col :span="2" class="alignRight">支付方式：</el-col>
              <el-col :span="4" class="alignLeft">{{ { 5: '对公转账', 10: '在线支付' }[param.paymentMethod] }}</el-col>
            </el-row>
            <el-row class="marginTop">
              <el-col :span="2" class="alignRight">箱型：</el-col>
              <el-col :span="4" class="alignLeft">{{ { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }[param.priceList[0]?.boxType] }}</el-col>
              <el-col :span="2" class="alignRight">下单日期：</el-col>
              <el-col :span="4" class="alignLeft">{{ param.createTime }}</el-col>
            </el-row>
        </el-col>
      </el-row>

    </el-card>
    <el-card class="marginTop20">
      <el-row style="font-weight: 700;font-size: 15px;">
        <el-col v-if="isAgent">客户信息</el-col>
        <el-col v-else>联系信息</el-col>
      </el-row>
      <el-row class="alignCenter">
          <el-col :span="24" v-if="isAgent">
            <el-row class="alignLeft marginTop">
              <el-col :offset="4" :span="6">企业名称</el-col>
              <el-col :span="10">{{ rowData.companyName }}</el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row class="alignLeft marginTop">
              <el-col :offset="4" :span="6">联系人</el-col>
              <el-col :span="10">{{ param.contacts }}</el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row class="alignLeft marginTop">
              <el-col :offset="4" :span="6">联系电话</el-col>
              <el-col :span="10">
                <template v-if="rowData.agentUserAreaCode">+{{rowData.agentUserAreaCode}}</template>
                {{ param.tel }}
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24" v-if="!isAgent">
            <el-row class="alignLeft marginTop">
              <el-col :offset="4" :span="6">支付方式</el-col>
              <el-col :span="10">{{ { 5: '对公转账', 10: '在线支付' }[param.paymentMethod] }}</el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row class="alignLeft marginTop">
              <el-col :offset="4" :span="6">留言</el-col>
              <el-col :span="10">{{ param.leaveMsg || '无' }}</el-col>
            </el-row>
          </el-col>
          <el-col :span="24" v-if="!isAgent">
            <el-row class="alignLeft marginTop">
              <el-col :offset="4" :span="6">联系客户</el-col>
              <el-col :span="10"><el-button type="primary" link plain icon="ChatDotSquare"></el-button></el-col>
            </el-row>
          </el-col>
          <el-col :span="24" v-else>
            <el-row class="alignLeft marginTop">
              <el-col :offset="4" :span="6">联系回调集装箱公司</el-col>
              <el-col :span="10"><el-button type="primary" link plain icon="ChatDotSquare"></el-button></el-col>
            </el-row>
          </el-col>
      </el-row>
    </el-card>
    <el-card v-if="!isAgent" class="marginTop20">
      <el-row>
        <el-col :span="24">
          <span style="font-weight: 700;font-size: 15px;">回箱人信息</span>
        </el-col>
      </el-row>
      <el-row class="marginTop20">
        <el-col :span="24">
          <el-row justify="center">
            <el-col :span="8">回箱人</el-col>
            <el-col :span="8">{{ user.nickname }}</el-col>
          </el-row>
        </el-col>
        <el-col :span="24" class="marginTop20">
          <el-row justify="center">
            <el-col :span="8"><redStar />操作员</el-col>
            <el-col :span="8">
              <el-select v-model="param.userSimple" @change="userSimpleChange" :disabled="!['boxOwnerSure'].includes(pageState)" style="width: 150px;">
                  <el-option v-for="(item,index) in param.userSimpleList" :key="index" :label="item.userName"
                    :value="item.userId">
                  </el-option>
                </el-select>
              </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>

    <!-- <el-card>箱使轨迹</el-card> -->

    <el-card v-if="!isAgent && ['boxOwnerSure', 'agentReject'].includes(pageState)" class="marginTop20">
      <el-row>
        <el-col  style="font-weight: 700;font-size: 15px;">超期费信息</el-col>
      </el-row>
      <el-row>
        <el-col :offset="6" :span="18" >
            超期 1 天，$
          <el-input-number v-model.trim="rowData.overdueFeeDay" :controls="false" :min="1" :max="999" :precision="0"
            @blur="rowData.overdueFeeDay = rowData.overdueFeeDay ? rowData.overdueFeeDay : 1" placeholder="< 1000"
            style="width: 80px" /> /箱/天
        </el-col>
        <el-col :offset="6" :span="18" class="marginTop20">
            超期
          <el-input-number v-model.trim="rowData.lossDay" :controls="false" :min="1" :max="999" :precision="0"
            @blur="rowData.lossDay = rowData.lossDay ? rowData.lossDay : 1" placeholder="< 1000"
            style="width: 80px; " />天后，仍未还箱，视为灭失，灭失费为 $
          <el-input-number v-model.trim="rowData.lossFee" :controls="false" :min="1" :max="9999" :precision="0"
            @blur="rowData.lossFee = rowData.lossFee ? rowData.lossFee : 1" placeholder="< 10000" style="width: 80px" />
        </el-col>
      </el-row>

    </el-card>
    <el-card v-else class="marginTop20">
      <el-row>
        <el-col :span="24" style="font-weight: 700;font-size: 15px;">超期费信息</el-col>
      </el-row>
      <el-row class="marginTop">
        <el-col :offset="6" :span="18">超期 1 天，${{ rowData.overdueFeeDay }} /箱/天</el-col>
        <el-col :offset="6" :span="18" class="marginTop">超期{{ rowData.lossDay }}天后，仍未还箱，视为灭失，灭失费为 $ {{ rowData.lossFee }}</el-col>
      </el-row>
    </el-card>
    
    <el-card class="marginTop20">
      <span style="font-weight: 700;font-size: 15px;">箱贴信息</span>
      <el-row justify="center" class="marginTop">
        <el-col :span="8" class="alignCenter">箱贴金额</el-col>
        <el-col :span="8"></el-col>
        <el-col :span="8" class="alignCenter numberlColor">${{rowData.amount}}</el-col>
      </el-row>
      <el-row justify="center" class="marginTop20" style="border-bottom: 1px solid #ccc;">
        <el-col :span="8" class="alignCenter">优惠券</el-col>
        <el-col :span="8"></el-col>
        <el-col :span="8" class="alignCenter">${{rowData.couponAmount}}</el-col>
      </el-row>
      <el-row justify="center" class="marginTop20" >
        <el-col :span="17"></el-col>
        <el-col :span="3" class="alignRight">合计</el-col>
        <el-col :offset="1" :span="3" class="alignLeft numberlColor">${{rowData.amount}}</el-col>
      </el-row>
      <el-row justify="center" class="marginTop20">
        <el-col :span="17"></el-col>
        <!-- <el-col :span="3" class="alignRight numberlColor">应收箱贴</el-col>
        <el-col :offset="1" :span="3" class="alignLeft numberlColor">${{rowData.actualPayAmount}}</el-col> -->
      </el-row>
    </el-card>
    <el-card v-show="isAgent" class="marginTop20"> <!--订单分配-->
      <orderAllocation ref="allocationRef" :rowData="rowData" :userSimpleList="param.userSimpleList" :allocation1="param.allocation1" :disabled="true"></orderAllocation>
    </el-card>
    <el-card style="width:100%;margin-top: 10px;"> <!-- 确认信息 暂未优化 -->
      <span
        v-if="['boxOwnerCheck', 'agentCheck', 'boxOwnerCheck2', 'agentCheck2', 'agentReviewReject', 'boxOwnerReviewReject', 'agentReviewReject2', 'boxOwnerReviewReject2'].includes(pageState)"
        style="font-weight: 700;font-size: 15px;">
        审核信息
      </span>
      <!-- <span v-else style="font-weight: 700;font-size: 15px;">
        <template v-if="param.isShow">确认信息</template>
      </span> -->

      <!-- 取消原因 -->
      <div v-if="showCancelRemark" style="text-align: center;margin-bottom: 20px;">
        <span> 取消原因： </span>
        <span>{{ rowData.remark }} </span>
        <div style="margin-top: 10px; ">
          <el-button @click="handleShowWarning('rejectOrder')" type="danger" > 拒绝 </el-button>
          <el-button @click="handleMakeSure" type="primary"> 同意 </el-button>
        </div>
      </div>
      <!-- 拒绝原因/驳回原因-->
      <div v-if="rowData.rejectReason && [5, 10].includes(rowData.currentNodeType)" style="text-align: center;">
        <span v-if="['agentReject', 'agentReject2'].includes(pageState)">拒绝原因：{{ rowData.rejectReason }}</span>
        <span
          v-if="['agentReviewReject', 'boxOwnerReviewReject', 'agentReviewReject2', 'boxOwnerReviewReject2'].includes(pageState)">
          驳回原因：{{ rowData.rejectReason }}
        </span>
      </div>
      <!-- 驳回原因 -->
      <!-- {{rowData.currentNodeType}}-----{{rowData.frontNodeType}}-- -->
      <div v-if="(isAgent && rowData.currentNodeType == 20) || (!isAgent && rowData.currentNodeType == 25)"
        style="width: 80%;margin: 0 auto;">
        <h4>
          <redStar />驳回原因
        </h4>
        <el-input type="textarea" :rows="4" v-model="rowData.reviewRemark" placeholder="请输入驳回原因" />
      </div>

      <!-- 一审核、取消 流程btn -->
      <!-- <div v-if="rowData.status <= 15 || rowData.status == 40" style="width:100%;text-align: center;margin-top: 10px;"> -->
      <div v-if="rowData.status < 15 || rowData.status == 40" style="width:100%;text-align: center;margin-top: 10px;">
        <template v-if="!isAgent">  <!--订单来源为集装箱公司-->
          <div style="margin-top: 10px;">
            <template v-if="rowData.currentNodeType == 10">
              <template v-if="rowData.frontNodeReviewStatus == 5">
                <UserAgreement @updateCheck = "updateData"></UserAgreement>
                <el-button v-if="rowData.status <= 5" @click="handleShowWarning('cancelOrder')" type="info">取消订单</el-button>
                <el-button v-if="rowData.status < 5" @click="handleSyncPriceList" type="primary">确认</el-button>
              </template>
              <template v-if="rowData.frontNodeReviewStatus == 10 && rowData.status != 40">
                <UserAgreement @updateCheck = "updateData"></UserAgreement>
                <el-button @click="handleShowWarning('cancelOrder')" type="info">取消订单</el-button>
                <el-button @click="handleSyncPriceList" type="primary"> 确认
                </el-button>
              </template>
            </template>
            <template v-if="rowData.currentNodeType == 15" style="margin-top: 10px;">
              <el-button @click="handleShowWarning('cancelOrder')" type="info">取消订单</el-button>
            </template>
           
            <template v-if="rowData.currentNodeType == 25" style="margin-top: 10px;">
              <UserAgreement @updateCheck = "updateData"></UserAgreement>
              <el-button @click="handleShowWarning('checkReject')" type="danger">驳回</el-button>
              <el-button @click="handleMakeSure" :disabled="param.isShowMakeSureBtn" type="primary">通过</el-button>
            </template>
            <el-button v-if="rowData.currentNodeType == 30 && rowData.status == 3" @click="handleLoadingShowContract" type="primary">签署</el-button>
            <el-button v-if="rowData.currentNodeType == 30 && rowData.status == 3" @click="completeSigning(rowData.id)" type="primary">完成签署</el-button>
            <template v-if="[5, 10].includes(rowData.status)" style="margin-top: 10px;">
              <el-button @click="handleShowWarning('cancelOrder')" type="info">取消订单</el-button>
            </template>
            <el-button v-if="rowData.status >= 5 && rowData.status <= 15" @click="handlePacking" type="primary">开提箱单</el-button>
          </div>
        </template>
        <!-- 货代-------- -->
        <template v-else>
          <template v-if="rowData.currentNodeType == 5">
            <UserAgreement @updateCheck = "updateData"></UserAgreement>
            <el-button @click="handleShowWarning('cancelOrder')" type="info" round>取消订单</el-button>
            <el-button @click="handleMakeSure" :disabled="param.isShowMakeSureBtn" type="primary">确认</el-button>
          </template>
          <template v-if="rowData.currentNodeType == 10" style="margin-top: 10px;">
            <el-button @click="handleShowWarning('cancelOrder')" type="info">取消订单</el-button>
          </template>
          <template v-if="rowData.currentNodeType == 15" style="margin-top: 10px;">
            <UserAgreement @updateCheck = "updateData"></UserAgreement>
            <el-button @click="handleShowWarning('cancelOrder')" type="info">取消订单</el-button>
            <el-button @click="handleShowWarning('rejectOrder')" type="danger"> 拒绝 </el-button>
            <el-button @click="handleMakeSure" :disabled="param.isShowMakeSureBtn" type="primary">确认</el-button>
          </template>
          <template v-if="rowData.currentNodeType == 20" style="margin-top: 10px;">
            <UserAgreement @updateCheck = "updateData"></UserAgreement>
            <el-button @click="handleShowWarning('checkReject')" type="danger">驳回</el-button>
            <el-button @click="handleMakeSure" :disabled="param.isShowMakeSureBtn" type="primary">通过</el-button>
          </template>
          <template v-if="rowData.currentNodeType == 25">
            <el-button @click="handleShowWarning('cancelOrder')" type="info" round>取消订单</el-button>
          </template>
          <template v-if="rowData.currentNodeType == 30">
            <el-button v-if="rowData.status == 3" @click="handleLoadingShowContract" type="primary"> 签署
            </el-button>
            <el-button v-if="rowData.status == 3" @click="completeSigning(rowData.id)" type="primary">完成签署</el-button>
            <el-button v-if="rowData.frontNodeType == 25 && [15, 20].includes(rowData.status)" @click="handleMakeSure"
              type="primary"> 确认
            </el-button>
          </template>
          <template v-if="[5, 10].includes(rowData.status)" style="margin-top: 10px;">
            <el-button @click="handleShowWarning('cancelOrder')" type="info" round>取消订单</el-button>
          </template>
        </template>
      </div>

      <!-- 二审、取消 -->
      <!-- 当前节点类型 currentNodeType 5-集装箱公司操作员提交 10-货代操作员确认 15-集装箱公司操作员确认 20-货代管理员审核 25-集装箱公司管理员审核 30-E签宝解约签章 35-E签宝重新签约签章 -->
      <!-- 上一个节点类型 frontNodeType 5-集装箱公司操作员提交 10-货代操作员确认 15-集装箱公司操作员确认 20-货代管理员审核 25-集装箱公司管理员审核 30-E签宝解约签章 35-E签宝重新签约签章 -->
      <div v-if="[15, 20].includes(rowData.status)" style="width:100%;text-align: center;margin-top: 10px;">
        <template v-if="isAgent">
          <div style="margin-top: 10px;">
            <template v-if="rowData.currentNodeType == 10">
              <template v-if="rowData.frontNodeReviewStatus == 5">
                <el-button @click="handleShowWarning('rejectOrder')" type="danger"> 拒绝</el-button>
                <el-button @click="handleMakeSureAndSavePriceList" type="primary">1确认</el-button>
              </template>
              <template v-if="rowData.frontNodeReviewStatus == 10 && rowData.status != 40">
                <el-button @click="handleMakeSureAndSavePriceList" type="primary"> 确认</el-button>
              </template>
            </template>
            <template v-if="rowData.currentNodeType == 20">
              <el-button @click="handleShowWarning('checkReject')" type="danger">驳回</el-button>
              <el-button @click="handleMakeSure" :disabled="param.isShowMakeSureBtn" type="primary"> 通过
              </el-button>
            </template>
            <template v-if="rowData.currentNodeType == 30">
              <el-button @click="showContract(2)" type="primary" round> 解 约</el-button>
            </template>
            <el-button v-if="rowData.currentNodeType == 35" @click="showContract(3)" type="primary" round>
              签 署
            </el-button>
          </div>
        </template>
        <!-- 集装箱公司-------- -->
        <template v-else>
          <div v-if="rowData.remark && rowData.currentNodeType == 10 && rowData.frontNodeReviewStatus == 10"
            style="text-align: center;">
            <span>
              <redStar />拒绝原因3：
            </span>{{ rowData.remark }}
          </div>
          <template v-if="rowData.currentNodeType == 5">
            <el-button @click="handleMakeSureAndSavePriceList" type="primary">
              确 认</el-button>
          </template>
          <template v-if="rowData.currentNodeType == 15" style="margin-top: 10px;">
            <el-button @click="handleMakeSureAndSavePriceList" type="primary">
              确 认</el-button>
          </template>
          <template v-if="rowData.currentNodeType == 25">
            <el-button @click="handleShowWarning('checkReject')" type="danger">驳回</el-button>
            <el-button @click="handleMakeSure" type="primary" :disabled="param.isShowMakeSureBtn">通过
            </el-button>
          </template>
          <template v-if="rowData.currentNodeType == 30">
            <el-button @click="handleDeleteContract" type="primary">解约</el-button>
          </template>
          <template v-if="rowData.currentNodeType == 35">
            <el-button @click="applyConContract2" type="primary"> 签署 </el-button>
            <el-button @click="completeSigning(rowData.id)" type="primary">完成签署</el-button>
          </template>
        </template>
      </div>
    </el-card>

    <!-- 签署 -->
    <el-dialog v-model="param.dialogVisible" width="500">
      <el-form :model="param">
        <el-form-item label="签署人姓名">
          <el-input v-model="param.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="签署人电话">
          <el-input v-model="param.code" placeholder="请输入验证码" />
        </el-form-item>
        <el-form-item>
          <div style="background-color: #FFF2E7;padding: 5px;box-sizing: border-box;width: 100%">
            <el-icon style="color: #2158F3;">
              <WarningFilled />
            </el-icon> 请确认签署人是否正确，更改签署人将重新发起签署！<br>
            <a href="#" style="padding-left: 20px;color: #7CAFFF;">E签宝协议签订教程</a>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="param.dialogVisible = false">取消</el-button>
          <el-button @click="handleSign">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- E签宝 -->
    <el-dialog v-model="param.dialogEVisibleWarning" @closed="handleCloseEQianBao" title="提示" style="width: auto;">
      <iframe v-if="param.dialogEVisibleWarning" :src="param.longContractUrl" width="100%" height="800px"
        frameborder="0"></iframe>
    </el-dialog>
    <!-- 开提箱单 -->
    
    <el-drawer v-model="param.drawerPacking" :show-close="false" :destroy-on-close="true" size="40%" :with-header="false">
      <el-row>
        <el-col :span="6">
          <span class="_before">开提箱单</span>
        </el-col>
      </el-row>
      <el-row align="middle">
        <el-col :span="4"><redStar />提箱单类型</el-col>
        <el-col :span="8" >
          <el-radio-group v-model="param.packingType">
            <el-radio value = "5" size="large">自有箱</el-radio>
            <el-radio value = "15" size="large">外调箱</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <OwnBox v-if="param.packingType == '5' " :packingInfo="param.packingInfo"  :orderType="10" @closeDialog="closeDialog"></OwnBox> 
      <!--自有箱-->
      <ExternalBox v-if="param.packingType == '15'" :packingInfo="param.packingInfo" :orderType="10" @closeDialog="closeDialog"></ExternalBox>
    </el-drawer>
    <!-- 提箱单信息 -->
    <el-dialog v-model="param.drawerPackingShow" width="80%">
      <packingDataShow ref="packingDataShowRef" :orderId="rowData.id" :rowData="rowData" @handleClose="handleClose">
      </packingDataShow>
    </el-dialog>
    <!-- 还箱单信息 -->
    <el-dialog v-model="param.drawerReturnShow" width="80%">
      <returnDataShow ref="returnDataShowRef" :orderId="rowData.id" :rowData="rowData" @handleClose="handleClose">
      </returnDataShow>
    </el-dialog>
    <!-- 提示 -->
    <el-dialog v-model="param.dialogVisibleWarning" title="提示" style="width: 400px;">
      <el-form>
        <el-form-item v-if="param.warningName == 'cancelOrder'">
          <h3>确定取消订单吗？</h3>
        </el-form-item>
        <el-form-item prop="remark">
          <div style="width: 100%;">
            <span v-if="param.warningName == 'cancelOrder'">取消原因：</span>
            <span v-else-if="param.warningName == 'rejectOrder'">拒绝原因：</span>
            <span v-else>驳回原因：</span>
          </div>
          <el-input v-model="warningForm.remark" type="textarea" rows="3" max="200" show-word-limit placeholder="请输入"
            style="width: 300px;" />
        </el-form-item>
        <el-form-item v-if="param.warningName == 'cancelOrder'">
          <el-button @click="handleCancel" type="primary" style="float: right;width: 100px;"> 确定
          </el-button>
        </el-form-item>
        <el-form-item v-if="param.warningName == 'rejectOrder'">
          <el-button @click="handleReject('rejectOrder')" type="primary" style="float: right;width: 100px;"> 确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 解约 -->
    <el-dialog v-model="param.dialogDeleteContract" title="提示" style="width: 400px;">
      <el-form>
        <el-form-item>
          <h3>您确定要解约当前已签署订单申请协议吗？</h3>
        </el-form-item>
        <el-form-item label="解约原因：">
          <el-select v-model="param.deleteReason">
            <el-option v-for="item in param.deleteReasonList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="原因说明：">
          <el-input v-model="param.deleteReasonRemark" type="textarea" rows="3" max="200" show-word-limit
            placeholder="请输入" style="width: 300px;" />
        </el-form-item>
        <el-form-item style="text-align: center;width:100%">
          <el-button @click="param.dialogDeleteContract = false" type="primary" style="width: 100px;"> 取消
          </el-button>
          <el-button @click="deleteContract" type="primary" style="width: 100px;"> 确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import UserAgreement from '@/views/components/UserAgreement'
import { formatDate } from '@/utils'
import huiDiaoPriceList from '@/views/components/huiDiao/huiDiaoPriceList'
import { updateCallbackOrderPrice } from '@/api/boxCallBack/order'
import { launchEqbCallbackOrderContract, eqbTerminateContract } from '@/api/EQianBao/index.ts'
import { addCallbackOrderRreturnCity } from '@/api/boxCallBack/order'
import { getPackingListById } from '@/api/boxCallBack/order'
import redStar from '@/views/components/redStar.vue';
import orderAllocation from '@/views/components/order/orderAllocation.vue'
import { downloadIamge } from '@/utils/download'
import { computed, onActivated, onMounted, reactive, ref, watch, provide,getCurrentInstance  } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import orderInfo from '@/store/modules/order'
import Progress from '@/components/progress/index.vue'
import { addAgentCallbackOrder, getOrderData, getOrderPrices, updateCallbackOrder, cancelCallbackOrder } from '@/api/boxCallBack/order'
import { ElLoading, ElMessage } from 'element-plus';
import OwnBox from '@/views/components/packingList/ownBox.vue';
import ExternalBox from '@/views/components/packingList/externalBox.vue';
import packingDataShow from '@/views/components/packingDataShow.vue';
import returnDataShow from '@/views/components/returnDataShow.vue';
import { processApproved, processRejected } from '@/api/orderCheck/index'
import stamp from '@/views/components/stamp';
import stampCancel from '@/views/components/stamp/stampCancel';
import { getContractList, getEqbContractOrderInfoByOrderId, getEqbContractOrderInfoLongContractUrl } from '@/api/contract/eQianBao'
import {
  Plus,
  Delete,
  Edit,
  Message,
  Search,
  Download,
  Upload,
  Refresh,
  UploadFilled,
  ChatLineSquare
} from '@element-plus/icons-vue'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const user = userStore.getUser() //user信息

const router = useRouter()

const props = defineProps({
  isAgent: { //当前等角色  true 货代角色  false 集装箱公司角色
    type: Boolean,
    default: false
  }
})

const param = reactive({
  dialogDeleteContract: false,
  deleteReasonList: [//1 - 条款内容有误 2 - 印章选择错误 3 - 签署人信息错误 4 - 合作终止 5 - 其他
    { value: 1, label: '条款内容有误', },
    { value: 2, label: '印章选择错误', },
    { value: 3, label: '签署人信息错误', },
    { value: 4, label: '合作终止', },
    { value: 5, label: '其他', },
  ],
  isShow:true,
  coupon: 0,
  dialogVisible: false,
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: 5, label: '40HQ', },
    { value: 10, label: '40GP', },
    { value: 15, label: '20HQ', },
    { value: 20, label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '5', label: '全新', },
  ],
  boxConditionList: [],
  boxTypeList: [],
  allocationHistory: {},
  boxType: '',
  boxCondition: '',
  num: 0,
  page: 1,
  limit: 10,
  newStep: 1,
  period:"",
  radioVal: false,
  //订单分配 
  handleUserList: [{ "handleUserId": 4, "handleUserName": "李四" }],
  // operateUsers: [],
  operateUserList: [{ "operateUserId": 3, "operateUserName": "张三" }, { "operateUserId": 5, "operateUserName": "王五" }],
  // businessUser: '',
  businessUserList: [{ "businessUserId": 4, "businessUserName": "李四" }, { "businessUserId": 6, "businessUserName": "赵六" }],
  // businessNo: '',
  allocation: [{ boxUsagePeriod: '', returnCity: '', number: 0, boxType: 5, boxCondition: 5, price: 0, xiaoJi: 0 }],
  packingType:"5",
  packingInfo:[], // 需开提箱单信息
  priceList:[],
  planPickupDate:'',
  boxUsagePeriod:''
})

const cheangeBoxUsagePeriod = (e) => {
  param.priceList[0].boxUsagePeriod = e.target.value
  param.boxUsagePeriod = e.target.value
}

//内置页面状态
const pageState = computed(() => {
  const currentNodeType = rowData.value.currentNodeType //回调箱货代下单:5-货代操作员提交 10-集装箱公司操作员确认 15-货代操作员确认 20-货代管理员审核 25-集装箱公司管理员审核 30-E签宝签章
  console.log(rowData,currentNodeType)
  const frontNodeType = rowData.value.frontNodeType
  const frontNodeReviewStatus = rowData.value.frontNodeReviewStatus
  const isCheck2 = rowData.value.processBusinessType == 50 // 修改城市引起的二审
  //  (processBusinessType 审批业务类型(10 - 回调审核 30 - 回调箱集装箱公司取消订单 35 - 回调箱货代取消订单  50 - 回调箱修改城市审核))
  let result = ''
  if (!isCheck2) {
    // 一审
    switch (currentNodeType) {
      case 10:
        if (frontNodeType == 5) {
          result = 'boxOwnerSure' // 待集装箱公司确认
        }
        if (frontNodeType == 15) {
          result = 'agentReject' //货代已拒绝 - 待集装箱公司确认
        }
        if (frontNodeType == 20) {
          result = 'boxOwnerReviewReject' // 集装箱公司已驳回 - 待集装箱公司确认
        }
        if (frontNodeType == 25) {
          result = 'agentReviewReject' // 货代已驳回 - 待集装箱公司确认
        }
        break
      case 15:
        if (frontNodeType == 10) {
          result = 'agentSure'// 待货代确认
        }
        break
      case 20:
        if (frontNodeType == 15) {
          result = 'boxOwnerCheck'// 待集装箱公司审核
        }
        break
      case 25:
        if (frontNodeType == 20) {
          result = 'agentCheck'// 待货代审核
        }
        break
      case 30:
        if (frontNodeType == 25) {
          result = 'qianZhang'// 待E签宝签章
        }
        break
      default:
        result = ''
    }
  } else {
    // 二审
    switch (currentNodeType) {
      case 5:
        if (frontNodeType == 10) {
          result = 'agentReject2' // 货代已拒绝 - 待集装箱公司确认
        }
        if (frontNodeType == 20) {
          result = 'agentReviewReject2' // 货代已驳回 - 待集装箱公司确认
        }
        if (frontNodeType == 25) {
          result = 'boxOwnerReviewReject2' // 集装箱公司已驳回 - 待集装箱公司确认
        }
        break
      case 10:
        if (frontNodeType == 5) {
          result = 'agentSure2' // 待货代确认
        }
        break
      case 15:
        if (frontNodeType == 10) {
          result = 'agentSure'// 待货代确认
        }
        break
      case 20:
        if (frontNodeType == 15) {
          result = 'boxOwnerCheck'// 待集装箱公司审核
        }
        break
      case 25:
        if (frontNodeType == 20) {
          result = 'agentCheck'// 待货代审核
        }
        break
      case 30:
        if (frontNodeType == 25) {
          result = 'qianZhang'// 待E签宝签章
        }
        break
      default:
        result = ''
    }
  }
  return result
})

const isDisabled = computed(() => {
  if (props.isAgent) return true // 货代禁止修改 
  if (rowData.value.processBusinessType == 50) return true // 二审禁止修改
  if (rowData.value.currentNodeType == 10) {
    return ![5, 15, 20, 25].includes(rowData.value.frontNodeType)
  }
  if (rowData.value.currentNodeType == 20) {
    return ![20].includes(rowData.value.frontNodeType)
  }

  return true
})

//E签宝关闭
const handleCloseEQianBao = () => {
  // location.reload()
  getSetBoxInfo()
}

// 判断新增抵达城市
const isShowCheck2 = computed(() => {
  if (rowData.value.status < 5) return false
  if (!param.priceList || param.priceList.length == 0) return false
  let index = param.priceList.findIndex((item: any) => item.id == null)
  return index > -1
})
// 取消原因展示判断
const showCancelRemark = computed(() => {
  if (rowData.value.status != 40) return false
  if (rowData.value.frontNodeType != 5) return false
  if (props.isAgent) {
    if (rowData.value.canceledType == 5) return true
  } else {
    if (rowData.value.canceledType == 10) return true
  }
  return false
})

//show 提示窗口
const warningForm = ref({})
const handleShowWarning = (val: String) => {
  if (val == 'cancelOrder' || val == 'rejectOrder') { //取消订单、拒绝
    param.dialogVisibleWarning = true
    param.warningName = val
  }
  if (val == 'checkReject') { //审核驳回
    handleReject('checkReject')
  }
}

// packingAllocationQuantity  // 已开过提箱单的箱量
// packedQuantity   // 已提箱量 / 需还箱量
// returnedQuantity // 已还箱量
// returnedPay  
const progressConfig = reactive({
  packingAllocationQuantity: 0,
  packedQuantity: 0,
  returnedPay:0,
  returnedQuantity:0,
})
const mainFileList = ref([])
onActivated(() => {
  param.radioVal = true
  getSetBoxInfo()
})

// 获取数据
let rowData = ref({})
const getSetBoxInfo = async () => {
  const id = orderInfo().rowData.id
  param.userSimpleList = orderInfo().rowData.userSimpleList

  if(orderInfo().rowData.allocation){
    let arr = []
    JSON.parse(orderInfo().rowData.allocation).forEach((item) => {
      let oper = []
      if(item.operateUser){
        item.operateUser.forEach((item:any) => {
          oper.push(item.operateUserId)
        })
      }
      arr.push({"businessNo":item.businessNo,"businessUser":item.businessUserId,"operateUsers":oper})
    })

    param.allocation1  = arr
  }
  if (!id) return
  await getOrderData(id).then((res: any) => {
    if (res && res.data) {
      param.packingInfo = []
      const row = res.data
      // rowData.value = JSON.parse(JSON.stringify(row))
      rowData.value = res.data
      param.packingInfo.push(res.data)
      progressConfig.packingAllocationQuantity = res.data.packingAllocationQuantity
      progressConfig.packedQuantity = res.data.packedQuantity
      progressConfig.returnedPay = res.data.returnedPay
      progressConfig.returnedQuantity = res.data.returnedQuantity
      if(res.data.status >= 3){
        param.radioVal = true
      }
      param.newStep = row.status
      mainFileList.value = JSON.parse(row.mainFileList)
      param.allocation = JSON.parse(row.allocation) || [{}]
      param.period = res.data.period

      param.handleUser = param.allocation[0]?.handleUserId
      param.planPickupDate = formatDate(row.planPickupDate, 2)
      param.createTime = formatDate(row.createTime, 2)
      param.agentName = res.data.agentName
      param.paymentMethod = row.paymentMethod + '' //支付方式
      param.tel = row.tel
      param.boxUsagePeriod = res.data.boxUsagePeriod
      param.contacts = row.contacts
      param.leaveMsg = row.leaveMsg
      totalMoney.value = row.totalMoney  // 没返回 考虑去掉
      param.carryCityList = [{ cityId: row.carryCityId, cityName: row.carryCityName, carryCountry: row.carryCountryId, carryCountryName: row.carryCountryName }]
      param.carryCity = param.carryCityList[0].cityId
      param.isShowMakeSureBtn = false

      
      getOrderPrices({ "orderId": row.id, "orderNo": row.orderNo }).then((res: any) => {
        let data = res.data
        param.priceList = []
        param.returnCityList = []
        data.forEach((item: any) => {
          param.returnCityList.push({ cityId: item.returnCityId, cityName: item.returnCityName, returnCountry: item.returnCountryId, returnCountryName: item.returnCountryName })
          let piiceInfo = {
            boxUsagePeriod: item.boxUsagePeriod,
            returnCity: item.returnCityId,
            number: item.boxQuantity,
            boxType: item.boxType,
            boxCondition: item.boxCondition,
            price: item.unitPrice || 1,
            xiaoJi: item.unitSubtotal,
            realReturnBoxQuantity: item.realReturnBoxQuantity || 0,
            id: item.id,
            currency:item.currency,
            returnCountry: item.returnCountryId,
            returnCityName: item.returnCityName,
            returnCountryName: item.returnCountryName
          }
          param.priceList.push(piiceInfo)
          getTotalMoney()
        })
      })
      userSimpleChange(rowData.value.boxEastOperatorUserId)
    }
  })
}

//操作员变更
const userSimpleChange = (val: any) => {
  if (!val) return
  const index = param.userSimpleList.findIndex((item: any) => {
    return item.userId == val
  })
  param.userSimpleData = param.userSimpleList[index]
  param.userSimple = val
}




//
const handlePacking = () => {
  // param.packingInfo = []
  // let info = {
  //   orderType: 10, //回调订单- 开提箱单
  //   boxType: param.priceList[0].boxType,
  //   boxCondition: param.priceList[0].boxCondition,
  //   planPickupDate: param.planPickupDate,
  //   agentName: param.agentName,
  //   createTime: param.createTime,
  //   priceList: param.priceList,
  //   orderNo: rowData.value.orderNo,
  //   id: rowData.value.id, // 订单id
  //   boxQuantity: rowData.value.boxQuantity,
  //   packingAllocationQuantity: rowData.value.packingAllocationQuantity,
  // }
  // param.packingInfo.push(info)
  
  param.drawerPacking = true
}
const packingInfoStr = () => {
  return param.packingInfo
}
provide('packingInfo', packingInfoStr);
provide('config', {
  disable:true, // 订单选择弹窗 筛选项是否可选
  sources: "internal", // 组件引用来源： internal-订单内开提箱单 ， management -体箱管理内开提箱单
  orderType: 10, // 订单类型 5：租箱 10：回调箱 
  
});
const drawerConfig = {
  citingSources: "boxEastOrderInfo",
  type: 0  // 0：订单内开提箱单 1:提箱单管理内开提箱
}
const successPacking = (id: any) => {
  param.newStep = 10
  getSetBoxInfo()
  param.drawerPacking = false
  // console.log(id)
}

//总回调箱量
const totalQuantity = computed(() => {
  let num = 0
  if (!param.priceList) return num
  param.priceList.forEach((item: any) => {
    num += (item.number - 0)
  })
  return num
})
// 待还箱量回调
const  needsReturnQuantity = computed(() => {
  let num = 0
  if (!param.priceList) return num
  param.priceList.forEach((item: any) => {
    num += (item.realReturnBoxQuantity - 0)
  })
  return num
})
//可添加总量
const couldAddQuantity = computed(() => {
  let num = 0
  param.priceList.forEach((item: any) => {
    num += (item.number - 0)
  })
  return (rowData.value.boxQuantity - 0) - num
})

//查看提箱单 
const packingDataShowRef = ref({ showPacking: () => { } })
const showPacking = () => {
  param.drawerPackingShow = true
  packingDataShowRef.value.showPacking()
}
//查看还箱单 
const returnDataShowRef = ref({ showReturn: () => { } })
const showReturnInfo = () => {
  param.drawerReturnShow = true
  returnDataShowRef.value.showReturn()
}

//一审 回调订单(价格&&箱使期)更新
const handleSyncPriceList = () => {
  if(!param.radioVal) return ElMessage.warning('请先阅读《集装箱租赁业务规则》、《用户服务协议和管理规则》并同意全部条款')
  handleMakeSure()
};
//二审 价格列表更新
const handleMakeSureAndSavePriceList = () => {
  param.isShowMakeSureBtn = false
  let priceList = []
  param.priceList.forEach((item: any) => {
    priceList.push({
      unitPrice: item.price,
      id: item.id,
    })
  })
  updateCallbackOrderPrice({ callbackOrderPriceBeans: priceList }).then(() => {
    handleMakeSure()
    param.isShowMakeSureBtn = true
  }).catch(() => {
    param.isShowMakeSureBtn = true
    ElMessage.error('价格保存失败')
  })
};

//一审 签署
const handleLoadingShowContract = async () => {
  // showContract()
  // return
  const loading = ElLoading.service({
    lock: true,
    text: '合同生成中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  await setTimeout(async () => {
    showContract()
    loading.close()
  }, 10000)
};

//待确认->通过、确认 btn
const allocationRef = ref({ allocation: [], onSubmit: () => { }, getAllocationTemplate: () => { } })
const handleMakeSure = async () => {
  if(!param.radioVal) return ElMessage.warning('请先阅读《集装箱租赁业务规则》、《用户服务协议和管理规则》并同意全部条款')
  const loading = ElLoading.service({
    lock: true,
    text: '数据请求中，请稍后....',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  param.isShowMakeSureBtn = false
  if (props.isAgent) { // 货代校验项
    if (!param.priceList || param.priceList.length == 0 || !param.priceList[0].boxUsagePeriod) {
      return ElMessage.warning('箱使期不能为空')
    }
    if (!rowData.value.rate) return ElMessage({ message: '请先确认 执行汇率', type: 'warning' })
    const allocationValidate = await allocationRef.value.onSubmit()
    if (!allocationValidate) {
      ElMessage.warning('订单分配 校验未通过')
      return
    }
    if (couldAddQuantity.value < 0) {
      ElMessage.error('总数量不能大于订单回调箱总量')
      return
    }
  }

  if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
  const data = { "processId": rowData.value.processId }
  if (rowData.value.status < 5 && !props.isAgent) { // 集装箱公司 一审时提交下的保存pricelist
    if (!param.userSimple) return ElMessage.warning('请选择操作员!')
    const updateOrderSucess = await handleUpdateOrder() //更新订单
    if (!updateOrderSucess) return ElMessage({ message: '保存失败！', type: 'error' })
  }
  processApproved(data).then(() => {
    param.isShowMakeSureBtn = true
    loading.close()
    ElMessage({ message: '确认成功', type: 'success' })
    getSetBoxInfo()
  }).catch(() => {
    param.isShowMakeSureBtn = true
  })
}
//待确认->拒绝btn、审核->驳回
const handleReject = (val: String) => {
  if (val == 'rejectOrder') { //拒绝
    if (!warningForm.value || !warningForm.value.remark) {
      return ElMessage({ message: '请输入拒绝 原因', type: 'warning' })
    }
    if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
    const data = { "processId": rowData.value.processId, "reviewRemark": warningForm.value.remark }
    processRejected(data).then(() => {
      ElMessage({ message: '驳回成功', type: 'success' })
      param.dialogVisibleWarning = false
      getSetBoxInfo()
      // orderInfo().setOrderInfo(rowData.value)
    })
  }
  if (val == 'checkReject') { //驳回
    if (!rowData.value || !rowData.value.reviewRemark) {
      return ElMessage({ message: '请输入驳回 原因', type: 'warning' })
    }
    if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
    const data = { "processId": rowData.value.processId, "reviewRemark": rowData.value.reviewRemark }
    processRejected(data).then(() => {
      ElMessage({ message: '驳回成功', type: 'success' })
      getSetBoxInfo()
    })
  }
}
// 取消订单
const handleCancel = () => {
  if (!warningForm.value || !warningForm.value.remark) {
    return ElMessage({ message: '请输入取消 原因', type: 'warning' })
  }
  const data = {
    id: orderInfo().rowData.id,
    remark: warningForm.value.remark
  }
  cancelCallbackOrder(data).then((res: any) => {
    ElMessage.success('取消申请已发送')
    param.dialogVisibleWarning = false
    getSetBoxInfo()
  })
}

//出发城市变更
const carryCityChange = (val: any) => {
  param.priceList = JSON.parse(JSON.stringify(param.priceListTemplate))
}
const handleClose = () => {
  param.drawerPackingShow = false
}

// 签署
const handleSign = () => {
  console.log('handleSign')
  let carryCity = {}
  param.carryCityList.forEach((item: any) => {
    if (item.cityId == param.carryCity) {
      carryCity = item
    }
  })
  const submitData = rowData.value.submitData
  let callbackOrderPriceList: any = []
  param.priceList.forEach((el: any) => {
    callbackOrderPriceList.push({
      "returnCityId": el.returnCity,
      "returnCityName": el.returnCityName,
      "returnCountryId": el.returnCountry,
      "returnCountryName": el.returnCountryName,
      "unitPrice": el.price - 0,
      "boxQuantity": el.number,
      "unitSubtotal": el.xiaoJi
    })
  })
  const data = {
    // "releaseRentId": rowData.value.id,
    "releaseCallbackId": rowData.value.id,
    "carryCityId": carryCity.cityId,
    "carryCityName": carryCity.cityName,
    "carryCountryId": carryCity.countryId,
    "carryCountryName": carryCity.countryName,
    "boxType": submitData.boxType,
    "boxCondition": submitData.boxCondition,
    "couponAmount": param.coupon,
    "planPickupDate": param.planPickupDate,
    "paymentMethod": param.paymentMethod,
    "contacts": param.contacts,
    "tel": param.tel,
    "leaveMsg": param.leaveMsg,
    "callbackOrderPriceBeans": callbackOrderPriceList
  }
  addAgentCallbackOrder(data).then((res: any) => {
    // console.log(res)
    router.push('/EQianBao_success')
  })
  param.dialogVisible = false
}

// 修改回调箱订单
const handleUpdateOrder = async () => {
  const callbackOrderPriceBeans = () => {
    let arry: any = []
    param.priceList.forEach((el: any) => {
      arry.push({
        "id": el.id,
        "unitPrice": el.price,
        "boxQuantity": el.number,
        "boxUsagePeriod": param.priceList[0].boxUsagePeriod,
        "returnCityName": el.returnCityName,
        "returnCityId": el.returnCity,
        "returnCountryName": el.returnCountryName,
        "returnCountryId": el.returnCountry
      })
    })
    return arry
  }
  const id = orderInfo().rowData.id
  let updateOrderSucess = false
  const userSimpleData = param.userSimpleData
  if (!userSimpleData.userId) return ElMessage.error('未获取到 操作员id信息 !')
  if (id) {
    const allocation = allocationRef.value.getAllocationTemplate()
    const data = {
      "id": id,
      "boxUsagePeriod": param.priceList[0].boxUsagePeriod,
      "callbackOrderPriceBeans": callbackOrderPriceBeans(),
      "allocation": JSON.stringify(allocation),
      "period":param.period,
      "overdueFeeDay": rowData.value.overdueFeeDay,
      "lossDay": rowData.value.lossDay,
      "lossFee": rowData.value.lossFee,
      "boxEastOperatorUserId": userSimpleData.userId,
      "boxEastOperatorUserName": userSimpleData.nickname,
      "boxEastOperatorUserAreaCode": userSimpleData.areaCode,
      "boxEastOperatorUserTel": userSimpleData.mobile,
      "planPickupDate": param.planPickupDate,
      "paymentMethod": param.paymentMethod,
      "contacts": param.contacts,
      "tel": param.tel,
      "leaveMsg": param.leaveMsg,
    }
    console.log('提交订单数据1111:',data)
    await updateCallbackOrder(data).then((res: any) => {
      updateOrderSucess = true
      // ElMessage.success('提交成功')
    })
  }
  return updateOrderSucess
}

//解约操作
const handleDeleteContract = async (val: any) => {
  await showContract(2)
  if (!param.longContractUrl) {
    param.dialogDeleteContract = true
  } else {
    if (props.isAgent) {
      ElMessage.warning('等待集装箱公司解约合同')
    }
  }
}

//解约函数
const deleteContract = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '解约合同生成中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  const data = {
    "userCompanyId": user.companyId,
    "orderId": rowData.value.id,
    "orderType": 10, // 订单类型 10-回调订单
    "signFlowId": rowData.value.signflowId,//"1356039bebbd43e084c00a8f95773668",
    "rescindReason": param.deleteReason,
    "rescindReasonNotes": param.deleteReasonRemark
  }
  eqbTerminateContract(data).then((res: any) => {
    ElMessage.success('解约合同生成完成')
    showContract(2) // 调取解约合同链接
    loading.close()
    getSetBoxInfo()
    param.dialogDeleteContract = false
  }).catch(err => {
    loading.close()
  })
}

// 签约调取 eQuanBao 长链接
// val 1-一审合同长链接 2-解约合同长链接 3-二审合同长链接
import useUserStores from '@/store/modules/user'
const showContract = async (type = 1) => {
  const userStore = useUserStores()
  const user = userStore.getUser() //user信息
  const data = {
    "orderId": rowData.value.id,
    "companyId": user.companyId,
    "businessType": 10
  }
  if (type == 2) {
    await getEqbContractOrderInfoByOrderId(data).then((res: any) => {
      const contractObj = res.data
      if (contractObj) {
        param.longContractUrl = contractObj.longTerminateUrl ? contractObj.longTerminateUrl : contractObj.longContractUrl //解约操作在后，优先显示解约合同
        if (param.longContractUrl) {
          param.dialogEVisibleWarning = true
        } else {
          if (props.isAgent) {
            ElMessage.warning('等待 集装箱公司解约合同')
          }
        }
      } else {
        // console.log(2222222)
        param.longContractUrl = null
        ElMessage.warning('系统繁忙！请稍后再试')
      }
    })
  } else {
    const loading = ElLoading.service({
      lock: true,
      text: '合同生成中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    await getEqbContractOrderInfoLongContractUrl(data).then((res: any) => {
      const contractObj = res.data
      loading.close()
      if (contractObj) {
        param.longContractUrl = contractObj.longTerminateUrl ? contractObj.longTerminateUrl : contractObj.longContractUrl //解约操作在后，优先显示解约合同
        if (param.longContractUrl) {
          param.dialogEVisibleWarning = true
        }
      } else {
        param.longContractUrl = null
        ElMessage.warning('系统繁忙！请稍后再试')
      }
    }).catch(err => {
      ElMessage.warning('系统繁忙！请稍后再试')
      loading.close()
    })
  }

}

// 二审 发起签约
const applyConContract2 = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '合同生成中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  launchEqbCallbackOrderContract({ orderId: rowData.value.id }).then(async (res: any) => {
    if (res.data) {
      param.longContractUrl = res.data
      param.dialogEVisibleWarning = true
      loading.close()
    } else {
      setTimeout(() => {
        launchEqbCallbackOrderContract({ orderId: rowData.value.id }).then(async (res: any) => {
          if(res.data){
            param.longContractUrl = res.data
            param.dialogEVisibleWarning = true
          }else{
            param.longContractUrl = null
            ElMessage.warning('合同生中，请稍后再试!')
          }
          loading.close()
        })
      }, 10000)
    }
  }).catch(err => {
    ElMessage.warning('合同生中，请稍后再试!')
    loading.close()
  })
}

//下载--------------- 
const downloadFile = async () => {
  let pdfFile = rowData.value.pdfFile || {}
  await getPackingListById(rowData.value.id).then((res: any) => {
    if (res.data[0].pdfFile) {
      pdfFile = JSON.parse(res.data[0].pdfFile)
    }
  })
  if (pdfFile) { //下载文件
    // console.log(pdfFile)
    if (!pdfFile || !pdfFile.url) return ElMessage.error('chengzhi 未找到文件')
    downloadIamge(pdfFile.url,pdfFile.originalFileName || new Date(Date.now()+28800000).toISOString())
  } else {
    console.log(rowData)
    ElMessage.error('chengzhi 未找到文件')
  }
}

//
const handleShowCheck2 = () => {
  // return
  let callbackOrderPriceBeans = []
  param.priceList.forEach((item: any) => {
    if (!item.id) {
      let itemInfo = {
        "unitPrice": item.price,
        "boxQuantity": 0,
        "returnCityId": item.returnCity,
        "returnCityName": item.returnCityName,
        "returnCountryId": item.returnCountry,
        "returnCountryName": item.returnCountryName
      }
      callbackOrderPriceBeans.push(itemInfo)
    }
  })
  const data = {
    id: rowData.value.id,
    callbackOrderPriceBeans: callbackOrderPriceBeans
  }
  addCallbackOrderRreturnCity(data).then((res: any) => {
    getSetBoxInfo()
  })
}

// 计算总价
let totalMoney = ref(0)
const priceListChange = (priceList) => {
  param.priceList = priceList
  getTotalMoney()
}
const getTotalMoney = () => {
  let arry = param.priceList
  totalMoney.value = 0
  arry.forEach((el) => {
    if (el.number >= 0 && el.price >= 0) {
      el.xiaoJi = el.number * el.price
      totalMoney.value = totalMoney.value - 0 + el.xiaoJi
    }
  })
  return arry
}

const updateData = (val) =>{
  param.radioVal = val
}
const closeDialog = () => {
  param.drawerPacking = false
}

const { proxy } = getCurrentInstance()
const completeSigning = (id) => { 
  let reqParam = { // 5:租箱 10：回调（进口） 15：购箱 
    orderId:id,
    businessType:10
  }
  proxy.$common(reqParam).then((res) => { 
    if(res.code === "00000"){
      ElMessage.success('操作成功')
    }else{
      ElMessage.warning(res.msg)
    }
  })
}

</script>
<style lang="scss" scoped>
.lookUp{
  margin: 0 !important ;
  padding: 20px 0;
  span{
    height: 40px;
  }
}
.pag-container {
  margin-top: 10px;
  box-sizing: border-box;
  padding: 10px;
}



.tableInfo>tr>td {
  min-width: 180px;
}

.alignLeft{
  text-align: left;
}
.alignRight{
  text-align: right;
}
.alignCenter{
  text-align: center;
}
.marginTop {
  margin-top: 10px;
}
.marginTop20{
  margin-top: 20px;
}
.numberlColor{
  color: cadet#2158F3;
}
</style>